<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/16
 * Time: 15:48
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\UserAddress;
use app\api\service\UserToken;
use app\api\validate\AddressNew;
use app\api\model\User as UserModel;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;
use app\api\service\Token as TokenService;



class Address extends BaseController
{
    /**
     * 前置方法判断
     * @var array
     */
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only','createOrUpdateAddress']
    ];

    /**
     * 添加或更新用户地址信息
     * @return \think\response\Json
     * @throws UserException
     */
    public function createOrUpdateAddress(){
        //1.根据传过来的token获取uid
        //2.根据uid查找用户数据，并判断用户是否存在，不存在则抛错
        //3.获取用户提交过来的用户信息
        //3.根据用户地址信息是否存在，判断是否更新还是添加
        $validate = new AddressNew();
        $validate->goCheck();
        $uid = UserToken::getCurrentUid();
        $user = UserModel::getUserInfoByUid($uid);
        if (empty($user)){
            throw new UserException();
        }
        $dataArray = $validate->getDataByRule(input('post.'));
        $userAddress = $user->address;
        if (empty($userAddress)){
            $user->address()->save($dataArray);//新增
        }else{
            $userAddress->save($dataArray);//更新
        }
        return json(new SuccessMessage(),201);
    }
    /**
     * 获取用户地址
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws UserException
     */
    public function getUserAddress(){
        $uid = TokenService::getCurrentUid();
        $address = UserAddress::getUserAddressByUID($uid);
        if (!$address){
            throw  new UserException([
                'msg' =>'用户地址不存在',
                'code'=>'60001'
            ]);
        }
        return $address;
    }
}